
use std::sync::{mpsc, Mutex,Arc};
use std::thread;
use std::time::Duration;


fn main() {
    let handle = thread::spawn( || {
        for i in 1..10 {
            println!("hi number {} from the spawned thread", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the spawned thread", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
    

    let v = vec![1,2,3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();


    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);

    let m = Mutex::new(5);

    {
        let mut  num = m.lock().unwrap();
        *num = 6;
    }

    println!("{:?}", m);

    let counter = Arc::new(Mutex::new(0));

    let mut handles = vec![];
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num +=1; 
        });
a
        handles.push(handle);
    }

    for ele in handles {
        ele.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
    
}
